<template>
  <div class="app-container">
    <el-row :gutter="12">
      <el-col :span="6">
        <el-card shadow="never">
          <div slot="header" class="clearfix">
            <span>商品类目</span>
          </div>
          <div class="block">
            <el-tree
              :data="productcategory"
              :props="productcategoryProps"
              node-key="id"
              default-expand-all
              :expand-on-click-node="false"
              @node-click="getProductcategoryData"
            />
          </div>
        </el-card>
      </el-col>
      <el-col :span="18">
        <div class="filter-container">
          <el-row>
            <el-input v-model="queryParam.title" placeholder="商品名称" clearable class="filter-item form-search-input" />
            <el-input v-model="queryParam.product_id" placeholder="SpuId" clearable class="filter-item form-search-input" />
            <el-select v-model="queryParam.status" clearable placeholder="状态" class="filter-item" style="margin-right: 5px">
              <el-option value="0" label="初始值" />
              <el-option value="5" label="上架" />
              <el-option value="6" label="回收站" />
              <el-option value="9" label="逻辑删除" />
              <el-option value="11" label="自主下架" />
              <el-option value="12" label="售磬下架" />
              <el-option value="13" label="违规下架/风控系统下架" />
            </el-select>
            <el-button  class="filter-item fr" icon="el-icon-refresh" @click="handleRefresh">
              重置
            </el-button>
            <el-button style="margin-right: 5px"  class="filter-item fr search" icon="el-icon-search" @click="handleSearch">
              搜索
            </el-button>
          </el-row>

        </div>
        <el-button v-if="this.selectedIds.length" size="small" class="filter-item mb-5" type="danger" icon="el-icon-delete" @click="handleMultiDelete">
          批量删除
        </el-button>
        <el-table
          ref="multipleTable"
          :data="data"
          tooltip-effect="dark"
          style="width: 100%"
          border
          fit
          @selection-change="handleSelectMulti"
        >
          <el-table-column type="selection" width="55" :selectable="selectInit"/>
          <el-table-column label="名称">
            <template slot-scope="products">{{ products.row.title }}</template>
          </el-table-column>
          <el-table-column
                  prop="product_id"
                  label="SpuId"
          />
          <el-table-column
            prop="min_price"
            label="价格"
          />
          <el-table-column
                  prop="stock"
                  label="库存"
          />
          <el-table-column
                  prop="sales_count"
                  label="销量"
          />
          <el-table-column prop="updated_at" label="修改时间" />
          <el-table-column prop="status" label="状态">
            <template slot-scope="products">
              <el-tag v-if="products.row.status === 0" type="success">初始值</el-tag>
              <el-tag v-if="products.row.status === 5" type="success">上架</el-tag>
              <el-tag v-if="products.row.status === 6" type="danger">回收站</el-tag>
              <el-tag v-if="products.row.status === 9" type="danger">逻辑删除</el-tag>
              <el-tag v-if="products.row.status === 11" type="danger">自主下架</el-tag>
              <el-tag v-if="products.row.status === 12" type="danger">售磬下架</el-tag>
              <el-tag v-if="products.row.status === 13" type="danger">违规下架/风控系统下架</el-tag>
            </template>
          </el-table-column>

          <el-table-column label="操作" fixed="right" width="300">
            <template slot-scope="products">
              <el-button type="primary" icon="el-icon-edit" v-else @click="beforeHandleUpdate(products.row)"/>
              <el-button type="danger" icon="el-icon-delete" v-else @click="handleDelete(products.row.id)"/>
              <el-button type="primary" icon="el-icon-refresh" @click="share(products.row.id)" >分享</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          background
          class="pagination-container"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="paginate.current"
          hide-on-single-page
          :page-sizes="paginate.sizes"
          :page-size="paginate.limit"
          :layout="paginate.layout"
          :total="paginate.total"/>
      </el-col>
    </el-row>
    <!----------------------------------- Products ---------------------------------------------->
    <el-dialog :close-on-click-modal="false" :title="title" :visible.sync="formVisible" :destroy-on-close="true"  @close="handleCancel()" >
      <el-form :ref="formName" :model="formFieldsData" :rules="rules">
        <el-row :gutter="12">
            <el-form-item label="商品类目" :label-width="formLabelWidth" prop="cats">
              <el-cascader
                      v-model="formFieldsData.cats"
                      :options="treeCategory.data"
                      :props="treeCategory.prop"
                      :show-all-levels="false"
                      style="width: 85%"
                      clearable/>
            </el-form-item>
          <el-form-item label="type" :label-width="formLabelWidth" prop="type">
            <el-select v-model="formFieldsData.brand_id" style="width: 85%" placeholder="请选择品牌" >
              <el-option v-for="(item, key) in type" :key="key" :label="item" :value="key"/>
            </el-select>
          </el-form-item>
            <el-form-item label="商品名称" :label-width="formLabelWidth" prop="title">
              <el-input v-model="formFieldsData.title" placeholder="请输入名称" autocomplete="off" clearable />
            </el-form-item>
            <el-form-item label="商品付标题（概述）" :label-width="formLabelWidth" prop="sub_title">
              <el-input v-model="formFieldsData.sub_title" placeholder="请输入商品概述" autocomplete="off" clearable />
            </el-form-item>

            <el-form-item label="商品属性">
              <avue-crud
              ref="crudHeader"
              :option="tableOption"
              :data="headerTableData"
              @row-update="addUpdateHeader"
              @row-del="rowDelHeader"
              @row-save="rowSaveHeader"
              >
                <template slot-scope="{ row, index }" slot="menu">
                  <el-button
                  type="text"
                  size="small"
                  @click="rowCellHeader(row, index)"
                  >{{ row.$cellEdit ? "自定义保存" : "自定义修改" }}</el-button
                  >
                </template>
              </avue-crud>
            </el-form-item>
            <el-form-item label="规格售价与库存">
              <avue-crud
              ref="crudBody"
              :option="tableOption"
              :data="bodyTableData"
              @row-update="addUpdateBody"
              @row-del="rowDelBody"
              @row-save="rowSaveBody"
              >
                <template slot-scope="{ row, index }" slot="menu">
                  <el-button
                  type="text"
                  size="small"
                  @click="rowCellBody(row, index)"
                  >{{ row.$cellEdit ? "自定义保存" : "自定义修改" }}</el-button
                  >
                </template>
              </avue-crud>
            </el-form-item>
          <el-form-item label="商品详情" :label-width="formLabelWidth" prop="document">
            <el-input type="textarea" :rows="5" v-model="formFieldsData.document" placeholder="请输入文档内容，markdown格式" autocomplete="off" clearable />
          </el-form-item>

            <el-form-item label="更多设置">
              <avue-crud
              ref="crudAuth"
              :option="tableOption"
              :data="authTableData"
              @row-update="addUpdateAuth"
              @row-del="rowDelAuth"
              @row-save="rowSaveAuth"
              >
                <template slot-scope="{ row, index }" slot="menu">
                  <el-button
                  type="text"
                  size="small"
                  @click="rowCellAuth(row, index)"
                  >{{ row.$cellEdit ? "自定义保存" : "自定义修改" }}</el-button
                  >
                </template>
              </avue-crud>
            </el-form-item>
          <el-form-item label="物流模板">
            <avue-crud
                    ref="crudQuery"
                    :option="tableOption"
                    :data="queryTableData"
                    @row-update="addUpdateQuery"
                    @row-del="rowDelQuery"
                    @row-save="rowSaveQuery"
            >
              <template slot-scope="{ row, index }" slot="menu">
                <el-button
                        type="text"
                        size="small"
                        @click="rowCellQuery(row, index)"
                >{{ row.$cellEdit ? "自定义保存" : "自定义修改" }}</el-button
                >
              </template>
            </avue-crud>
          </el-form-item>

          <el-form-item label="排序" :label-width="formLabelWidth" prop="sort">
            <el-input-number v-model="formFieldsData.sort" :min="1" :max="100000" />
          </el-form-item>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleCancel()">取 消</el-button>
        <el-button type="primary" @click="submit">保存草稿</el-button>
        <el-button type="primary" @click="submit">上架</el-button>
      </div> 
    </el-dialog>
  </div>
</template>
<script>
import formOperate from '@/layout/mixin/formOperate'
export default {
  name:'minishop_productmanagement',
  mixins: [formOperate],
  data() {
    return {
      formName: 'products',
      // 刷新路由
      refreshRoute: true,
      productcategoryProps: {
        label: 'name'
      },
      formLabelWidth: '120px',
      // api搜索
      queryParam: {
        title: '',
        product_id: '',
        status: '',
        edit_status: '',
        cats: ''
      },
      formVisible: false,
      formFieldsData: {
        title: '',
        sub_title: '',
        product_id: '',
        cats: [],
        shopcat: [],
        head_img: '',
        desc_info: '',
        brand_id: '',
        min_price: '',
        attrs: [],
        model: '',
        skus:'',
        sales_count:'',
        weigh:'',
        template_id:'',
        ext_json:'',
        sort:'',
        status:'',
        edit_status:''
      },
      url: 'apitester',
      data: [],
      // 分类
      treeCategory: {
        data: [],
        default: [],
        prop: {
          label: 'name',
          value: 'id',
          emitPath: false,
          checkStrictly: true
        }
      },
      // methods类型
      type: {
        1: 'remote',
        2: 'local'
      },
      // methods类型
      methodsTypes: {
        'POST': 'POST',
        'GET': 'GET',
        'PUT': 'PUT',
        'PATCH': 'PATCH',
        'DELETE': 'DELETE',
        'COPY': 'COPY',
        'HEAD': 'HEAD',
        'OPTIONS': 'OPTIONS'
      },
      content_types: {
        'application/x-www-form-urlencoded': 'application/x-www-form-urlencoded',
        'application/json; charset=utf-8': 'application/json; charset=utf-8',
        'multipart/form-data': 'multipart/form-data',
        'raw': 'raw'
      },
      // 表单验证
      rules: {
        api_title: [
          { required: true, message: '请输入名称', trigger: 'blur' },
          { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
        ],
        api_name: [
          { required: true, message: '请输入英文唯一标识', trigger: 'blur' }
        ]
      },
      // 分类
      productcategory: [],
      // ↓ api form 表单 ↓
      headerTableData: [],
      bodyTableData: [],
      queryTableData: [],
      authTableData: [],
      // ↓ api form 表单 Options ↓
      tableOption: {
        refreshBtn:false,
        addBtn: false,
        editBtn: false,
        addRowBtn: true,
        cancelBtn: false,
        border: true,
        column: [
          {
            label: "Key",
            prop: "key",
            cell: true,
            rules: [
              {
                required: true,
                message: "请输入Key值",
                trigger: "blur"
              }
            ]
          },
          {
            label: "Value",
            prop: "value",
            cell: true,
            rules: [
              {
                required: true,
                message: "请输入Value值",
                trigger: "blur"
              }
            ]
          }
        ]
      },
    }
  },
  // 初始化数据
  mounted() {
    this.$http.get('minishopProductCategory').then(response => {
      this.productcategory = response.data
    })
},
  methods: {
    // 获取分类API
    getProductcategoryData(data, node, self) {
      this.queryParam.category_id = data.id
      this.handleSearch()
    },
    // 禁用/启用
    disOrEnableApi(products) {
      this.$http.put('apitester/switch/status/' + products.id).then(response => {
        this.$message({
          message: response.message,
          type: 'success'
        })
      })
    },
    beforeCreate() {
      this.$http.get('apicategory').then(response => {
        this.treeCategory.data = response.data
      })
    },
    beforeHandleUpdate(api) {
      this.beforeCreate()
      this.$http.get(this.url + '/' + api.id).then(response => {
        const api = response.data
        this.handleUpdate(api)
      })
    },
    selectInit(row, index) {
      return row.id !== 0
    },
    submit() {
      this.handleSubmit()
    },
    onJsonChange (value) {
                   console.log('value:', value);
        },
    onJsonSave (value) {
        console.log('value:', value);
    },
    changeUserenv(env){
      this.$http.get('apiTesterUserenv/selectAPIenv/' + env).then(response => {

      })
    },
        // ↓ Header 表格 行编辑 ↓
    rowCellHeader(row, index) {
      this.$refs.crudHeader.rowCell(row, index);
    },
    rowCellBody(row, index) {
      this.$refs.crudBody.rowCell(row, index);
    },
    rowCellQuery(row, index) {
      this.$refs.crudQuery.rowCell(row, index);
    },
    rowCellAuth(row, index) {
      this.$refs.crudAuth.rowCell(row, index);
    },
    // ↓ Header 表格 编辑行数据 ↓
    addUpdateHeader(form, index, done, loading) {
      loading();
      done();
    },
    addUpdateBody(form, index, done, loading) {
      loading();
      done();
    },
    addUpdateQuery(form, index, done, loading) {
      loading();
      done();
    },
    addUpdateAuth(form, index, done, loading) {
      loading();
      done();
    },
    afterCancel(){
      setTimeout(()=>{
      this.headerTableData= [];
      this.bodyTableData= [];
      this.queryTableData= [];
      this.authTableData= [];
      },400);
      Object.keys(this.formFieldsData).forEach((k) => {
        switch (k) {
          case 'category_id':
            this.formFieldsData[k] = null
            break
          case 'type':
            this.formFieldsData[k] = '1'
            break
          default:
            break
        }
      })
    },
    // ↓ Header 表格 保存行数据 ↓
    rowSaveHeader(form, done) {
      done();
      let json = this.handlerTable(this.headerTableData)
      this.formFieldsData.header = json
    },
    rowSaveBody(form, done) {
      done();
      let json = this.handlerTable(this.bodyTableData)
      this.formFieldsData.body = json
    },
    rowSaveQuery(form, done) {
      done();
      let json = this.handlerTable(this.queryTableData)
      this.formFieldsData.query = json
    },
    rowSaveAuth(form, done) {
      done();
      let json = this.handlerTable(this.authTableData)
      this.formFieldsData.auth = json
    },
        // ↓ Header 表格 删除行数据 ↓
    rowDelHeader(form, index, done) {
      this.headerTableData.splice(index, 1);
      let json = this.handlerTable(this.headerTableData)
      this.formFieldsData.header = json
    },
    rowDelBody(form, index, done) {
        this.bodyTableData.splice(index, 1);
        let json = this.handlerTable(this.bodyTableData)
        this.formFieldsData.body = json
    },
    rowDelQuery(form, index, done) {
      this.queryTableData.splice(index, 1);
      let json = this.handlerTable(this.queryTableData)
      this.formFieldsData.query = json
    },
    rowDelAuth(form, index, done) {
      this.authTableData.splice(index, 1);
      let json = this.handlerTable(this.authTableData)
      this.formFieldsData.auth = json
    },
    // ↓ 处理 ApiBaseInfo Json数据格式 返回 Object 格式 ↓
    JsonToObject(json) {
      if (json&&json!=='') {
        let flag = /\'/.test(json);
        if (flag) {
          return JSON.parse(json.replace(/\'/gi, '"'));
        } else {
          return JSON.parse(json);
        }
      } else {
        return null;
      }
    },
    initTableData(json){
      let obj = this.JsonToObject(json)
      let arr = Object.entries(obj).map(item => {
        return { key: item[0], value: item[1], $cellEdit: false };
      });
      return arr
    },
    handlerTable(arr){
      let obj = {};
      if(arr){
        arr.forEach(item=>{
          return obj[item.key] = item.value
        })
      }
      if(Object.keys(obj).length){
        return JSON.stringify(obj)
      }else{
        return ""
      }
    }
  },
  watch:{
    formFieldsData:{
      handler(data){
        if(data.header){
          this.headerTableData = this.initTableData(data.header);
        }
        if(data.body){
          this.bodyTableData = this.initTableData(data.body);
        }
        if(data.auth){
          this.authTableData = this.initTableData(data.auth);
        }
        if(data.query){
          this.queryTableData = this.initTableData(data.query);
        }
      },
      deep:true
    },
    // headerTableData:{
    //   handler(data){
    //   let json = this.handlerTable(data)
    //     this.formFieldsData.header = json
    //   },deep:true
    // }
  },
}
</script>
<style>
  .custom-tree-node {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 14px;
    padding-right: 8px;
  }
</style>
